
import { getmessageHistory } from "@/server"
import { useRequest } from "ahooks"
import { useDispatch } from "react-redux"
import { useSelector } from "react-redux"
import { MessageType, setHistoryMessageList } from "@/store/MessageStore"
import { stateType } from "@/store"
import { nextTick } from "process"

const useLoadHistoryMessage = (userChatId: string,cb:any = null) => {
    const dispatch = useDispatch()
    const messageList = useSelector((state: stateType) => state.MessageReducer)
    const { run: loadHistoryMsg } = useRequest(() => {
        const topMsgId = messageList[0].id
        return getmessageHistory(userChatId, topMsgId.includes('local') ? '' : topMsgId)

    }, {
        refreshDeps: [userChatId],
        onSuccess(res: any) {
            const History = res.records.map((item: any) => {
                let obj: MessageType = {
                    id: item.id,
                    head: item.sendUserInfo.head,
                    nickname: item.sendUserInfo.nickname,
                    sendid: item.sendId,
                    time: item.time,
                    info: {}
                } as any
                if (item.sendId.includes('AI')) {
                    obj.info.type = "AI"
                    obj.info.value = item.text
                } else if (item.sendId.includes('USER') || item.sendId.includes('KEFU')) {
                    console.log('textjson',item)
                    const textjson = JSON.parse(item.text)
                   
                    if (textjson.type == 'text') {
                        obj.info.type = "text"
                    } else if (textjson.type == 'image') {
                        obj.info.type = "image"
                    }
                    obj.info.value = textjson.info
                }
                return obj
            })
            // console.log('History',History.reverse())
            dispatch(setHistoryMessageList(History))
            nextTick(()=>{
                cb && cb(messageList[0].id)
            })
        },
        manual: true
    })

    return {
        loadHistoryMsg
    }

}


export default useLoadHistoryMessage

